#include "comLib\NetPacket.h"
#include"string.h"
#include<assert.h>

NetPacket::NetPacket()
{
	m_iRealSize = 0;
}

void NetPacket::allocateBuf(uint bufSize){
	m_Ptr = new uchar[bufSize];
	this->m_iBufSize = bufSize;
}

void NetPacket::writeImage(uchar *buffer, int width, int height, int widthBytes)
{
	assert(buffer);
	checkBuffer(widthBytes*height);
	write(buffer, widthBytes*height);

	m_width = width;
	m_height = height;
	m_widthBytes = widthBytes;
}

void NetPacket::write(const uchar *buffer, uint bufSize){
	checkBuffer(bufSize);
	memcpy_s(m_Ptr + m_iRealSize, this->m_iBufSize - m_iRealSize, buffer, bufSize);
	m_iRealSize+= bufSize;
}

uint NetPacket::getInt(uint pos)
{
	uint *iData = (uint*)(m_Ptr + pos);
	return *iData;
}

void NetPacket::preAllocatBuf(uint bufSize)
{
	checkBuffer(bufSize);
	m_iRealSize = 0;
}

void NetPacket::checkBuffer(uint bufSize){
	if (bufSize > this->m_iBufSize)
	{
		uchar *tpPtr = new uchar[bufSize];
		memcpy(tpPtr, m_Ptr, m_iRealSize);
		m_iBufSize = bufSize;

		delete[]m_Ptr;
		m_Ptr = tpPtr;
	}
}
const uchar* NetPacket::getPtr(){
	return m_Ptr;
}
uint	NetPacket::getSize(){
	return m_iRealSize;
}

int NetPacket::getWidth()
{
	return m_width;
}

int NetPacket::getHeight()
{
	return m_height;
}

int NetPacket::getWidthBytes()
{
	return m_widthBytes;
}

int NetPacket::getChannel()
{
	int channel = -1;

	if (m_width!=0)
	{
		channel = m_widthBytes / m_width;
	}
	else
	{
		channel = -1;
	}

	return channel;
}

NetPacket::~NetPacket(){
	if (m_Ptr)
	{
		delete[]m_Ptr;
		m_Ptr = nullptr;
	}
}

void NetPacket::emptyBuf()
{
	m_iRealSize = 0;
}